package com.tanhua.dubbo.server.api.mongo;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Friend friend) {
        friend.setId(ObjectId.get());
        friend.setCreated(System.currentTimeMillis());
        mongoTemplate.save(friend);
    }

    @Override
    public PageResult findAll(Integer page, Integer pageSize, Long userId,String keyword) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Criteria criteria = Criteria.where("userId").is(userId);

        if(StringUtils.isNoneBlank(keyword)) {
            Pattern pattern = Pattern.compile("^.*" + keyword + ".*$");
            criteria.and("friendName").regex(pattern);
        }

        Query query = Query.query(criteria).with(pageRequest);
        List<Friend> usersList = this.mongoTemplate.find(query, Friend.class);

        Long counts = this.mongoTemplate.count(query, Friend.class);
        return new PageResult(page,pageSize, counts.intValue(), usersList);
    }
}
